package com.xu.atomic;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 *
 * @author xudenghui
 * @create 2023-02-28 9:04
 **/
public class AtomicIntegerDemo1 {

//    static AtomicReference<Integer> money = new AtomicReference<>();
    static AtomicStampedReference<Integer> money = new AtomicStampedReference<>(19,0);
    //设置账号初始值小于20元

    public static void test1(){
        for (int i = 0; i < 3; i++) {
            final int timestamp = money.getStamp();
            new Thread(){
                @Override
                public void run() {
                    while (true){
                        while (true){
                            Integer m = money.getReference();
                            if (m<20){
                                if (money.compareAndSet(m, m+20,timestamp,timestamp+1)){
                                    System.out.println("于额度小于20元，充值成功，余额："+money.getReference()+"元");
                                }
                                break;
                            }else{
                                System.out.println("于额大于20元，无须充值");
                                break;
                            }
                        }
                        try {
                            TimeUnit.MILLISECONDS.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();
        }
    }


    public static void test2(){
        new Thread(){
            @Override
            public void run() {
                final int timestamp = money.getStamp();
                for (int i = 0; i < 100; i++) {
                    while (true){
                        Integer m = money.getReference();
                        if (m>10){
                            System.out.println("大于10元，无须充值");
                            if (money.compareAndSet(m, m-10,timestamp,timestamp+1)){
                                System.out.println("成功消费10元，余额："+money.getReference()+"元");
                            }
                            break;
                        }else{
                            System.out.println("没有足够的金额");
                            break;
                        }
                    }
                    try {
                        TimeUnit.MILLISECONDS.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }


    public static void main(String[] args) {
        test1();
        test2();
    }
}
